package com.woniuxy.realm;

import java.util.HashSet;
import java.util.Set;

import com.woniuxy.entity.Coach;
import com.woniuxy.entity.User;
import com.woniuxy.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
/**
 * 吴毛伟原生态制造
 */

public class UserRealm extends AuthorizingRealm{
	@Autowired
	private UserService userService;
	//授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		Set<String> roles = new HashSet<>();
		roles.add("user");
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);
		return info;
	}
	//认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		CustomizedToken customizedToken = (CustomizedToken) token;
		String uname = customizedToken.getUsername();
		User userByUname = userService.findUserByUname(uname);
		if (userByUname == null) {
			throw new UnknownAccountException("用户不存在！");
		}
		String principal = uname;
		String credentials = new SimpleHash("MD5", userByUname.getPwd(), userByUname.getUname(), 1024).toString();
		System.out.println(credentials+"--------++++++++++++++------------------");
		String realmName = getName();
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(principal, credentials,
				realmName);
		return info;
	}

}
